import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'

Vue.use(Router)
const loadRoutes = files => files.keys()
    .reduce((arr, key) => {
        const routes = files(key).default;
        return typeof routes === 'object' ? arr.concat(routes) : arr;
    }, [])
    .sort((prev, next) => (prev.sort || 0) - (next.sort || 0));

let routes = [{
            path: '/',
            name: 'home',
            meta: {
                title: '首页',
                keepAlive: true
            },
            redirect: '/home',
            component: () =>
                import ('views/Home.vue'),
            children: loadRoutes(require.context('./home', false, /\.js$/)),
        },

        {
            path: '/404',
            name: '404',
            component: () =>
                import ('views/404.vue'),
            meta: {
                title: '404',
                keepAlive: true
            }
        }
    ]
    // 获取文件下所有路由
const routerContext = require.context('./', true, /\.js$/)
routerContext.keys().forEach(route => {
    // 如果是根目录的 index.js 、不处理
    if (route.startsWith('./index')) {
        return
    }
    const routerModule = routerContext(route)
        /**
         * 兼容 import export 和 require module.export 两种规范
         */
    routes = routes.concat(routerModule.default || routerModule)
})
routes = routes.concat({
    path: '*',
    redirect: '/404'
})

const createRouter = () => new Router({
    // mode: 'history', // require service support
    // 配置url 默认添加项 process.env.BASE_URL
    base: process.env.BASE_URL,
    routes
})
const myRouter = createRouter()
    // myRouter.beforeEach((to, from, next) => {
    //     if (to.meta.auth) {
    //         var isLogin = localStorage.getItem('user');
    //         console.log(isLogin);
    //         if (isLogin) {
    //             next();
    //             console.log('已经登录');
    //         } else {
    //             console.log('未登录');
    //             next();
    //         }
    //     } else {
    //         next()
    //     }
    // })

export function resetRouter() {
    myRouter.replace({
            name: 'login'
        })
        // console.log('退出');
}

export default myRouter